package com.nobuyme.box.downUpdata;

/**
 * Created by Administrator on 2017/4/11.
 */

import android.annotation.TargetApi;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.nobuyme.box.account.AccountManager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Response;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * helper methods.
 */
public class AppUpdateThread {
    private static boolean isRunning = false;
    public static OnProgressListener mProgressListener;

    public AppUpdateThread(){

    }

    public interface OnProgressListener {
        void onSuccess(boolean isSuccess);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static boolean startDownloade(String url, String remoteFilePath, String LocalfileName, OnProgressListener pregressListener) {
        LogE("开始升级----");
        LogE("url = " + url);
        LogE("remoteFilePath = " + remoteFilePath);
        LogE("LocalfileName = " + LocalfileName);
        if (isRunning) {
            LogE("isRunning 退出");
            if (mProgressListener != null) {
                mProgressListener.onSuccess(false);
            }
            return false;
        }
        isRunning = true;
        try {
            boolean isSuccess = downloadUpdateFile(url, remoteFilePath, LocalfileName, pregressListener);
            isRunning = false;
            if (isSuccess) {
//                silentInstall(fileName);//root后静默安装以及重启
//                rebootSU();
//                Uri uri = Uri.fromFile(new File(fileName));
//                Intent installIntent = new Intent(Intent.ACTION_VIEW);
//                installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
//                startActivity(installIntent);
            } else {
                LogE("下载失败");
                return true;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 下载文件
     *
     * @param downloadUrl
     * @param filepath
     * @return
     * @throws Exception
     */
    private static boolean downloadUpdateFile(String downloadUrl, String remotePath, final String filepath, final OnProgressListener mProgressListener) {
//        try {
            Map<String, Object> map = new HashMap<>();
            map.put("filePath", remotePath);
            OkHttpUtil.postDownFile(downloadUrl, map, new CallBackFileStream(){
                @Override
                public void onTResponse(Response response, InputStream mInputStream) {
                    if (mInputStream == null){
                        LogE("mInputStream == null");
                    }
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    try {
                        long total = response.body().contentLength();
                        LogE("total------>" + total);
                        if(total <= 0){
                            if (mProgressListener != null){
                                mProgressListener.onSuccess(false);
                            }
                            return;
                        }
                        long current = 0;
                        LogE("filepath = " + filepath);
                        File file = new File(filepath);
                        if (!file.exists()){
                            boolean newFile = file.createNewFile();
                            LogE("创建新文件 ret= " + newFile);
                        }
                        try{
                            fos = new FileOutputStream(filepath);
                        }catch (FileNotFoundException e){

                            //下载失败，设置下发false
                            AccountManager.getCurrentAccount().setIs_updata(false);
                            LogE("文件找不到");
                        }
                        LogE("开始字节流读写");
                        while ((len = mInputStream.read(buf)) != -1) {
                            //LogE("current------>" + current);
                            current += len;
                            fos.write(buf, 0, len);
                        }
                        LogE("下载成功");
                        fos.flush();
                        if (mProgressListener != null) {
                            mProgressListener.onSuccess(true);
                        }else{
                            LogE("mProgressListener == null");
                        }
                    } catch (IOException e) {
                        //下载失败，设置下发false
                        AccountManager.getCurrentAccount().setIs_updata(false);
                        LogE("IOException = " + e.toString());
                        if (mProgressListener != null) {
                            mProgressListener.onSuccess(false);
                        }
                    } finally {
                        try {
                            if (mInputStream != null) {
                                mInputStream.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException e) {
                            //下载失败，设置下发false
                            AccountManager.getCurrentAccount().setIs_updata(false);
                            LogE( "finally err = " + e.toString());
                        }
                    }
                }
                @Override
                public void onFailure(Exception arg1) {
                    LogE("onFailure = " + arg1.toString());
                    //下载失败，设置下发false
                    AccountManager.getCurrentAccount().setIs_updata(false);
                    if (mProgressListener != null) {
                        mProgressListener.onSuccess(false);
                    }
                }
            });
            return true;
    }

    public static void rebootSU() {
        Runtime runtime = Runtime.getRuntime();
        Process proc = null;
        OutputStreamWriter osw = null;
        StringBuilder sbstdOut = new StringBuilder();
        StringBuilder sbstdErr = new StringBuilder();

        String command="/system/bin/reboot";

        try { // Run Script
            proc = runtime.exec("su");
            osw = new OutputStreamWriter(proc.getOutputStream());
            osw.write(command);
            osw.flush();
            osw.close();

        } catch (IOException ex) {
            //下载失败，设置下发false
            AccountManager.getCurrentAccount().setIs_updata(false);
            ex.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            if (proc != null)
                proc.waitFor();
        } catch (InterruptedException e) {
            //下载失败，设置下发false
            AccountManager.getCurrentAccount().setIs_updata(false);
            e.printStackTrace();
        }

        sbstdOut.append(new BufferedReader(new InputStreamReader(proc
                .getInputStream())));
        sbstdErr.append(new BufferedReader(new InputStreamReader(proc
                .getErrorStream())));
        if (proc.exitValue() != 0) {
        }
    }


    public static void showDownSU() {
        Runtime runtime = Runtime.getRuntime();
        Process proc = null;
        OutputStreamWriter osw = null;
        StringBuilder sbstdOut = new StringBuilder();
        StringBuilder sbstdErr = new StringBuilder();

        String command="/system/bin/reboot -p";

        try { // Run Script
            proc = runtime.exec("su");
            osw = new OutputStreamWriter(proc.getOutputStream());
            osw.write(command);
            osw.flush();
            osw.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            if (proc != null)
                proc.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        sbstdOut.append(new BufferedReader(new InputStreamReader(proc
                .getInputStream())));
        sbstdErr.append(new BufferedReader(new InputStreamReader(proc
                .getErrorStream())));
        if (proc.exitValue() != 0) {
        }
    }



    public static boolean silentInstall(String apkPath) {
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        BufferedReader successStream = null;
        Process process = null;
        try {
            // 申请 su 权限
            process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行 pm install 命令     并且重启
//            String command = "pm uninstall -k com.insyte.bookrack" + "&& pm install -r " + apkPath + "&& ./system/bin/reboot" + "\n";
            String command = "pm install -r " + apkPath + "&& ./system/bin/reboot" + "\n";
//            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("UTF-8")));
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorMsg = new StringBuilder();
            String line;
            while ((line = errorStream.readLine()) != null) {
                errorMsg.append(line);
            }
            Log.e("AppUpdateService", errorMsg.toString());
            StringBuilder successMsg = new StringBuilder();
            successStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
            // 读取命令执行结果
            while ((line = successStream.readLine()) != null) {
                successMsg.append(line);
            }
            Log.e("AppUpdateService", successMsg.toString());
            // 如果执行结果中包含 Failure 字样就认为是操作失败，否则就认为安装成功
            if (!(errorMsg.toString().contains("Failure") || successMsg.toString().contains("Failure"))) {
                result = true;
            }
        } catch (Exception e) {
            Log.e("AppUpdateService", "错误1:" + e.toString());
        } finally {
            try {
                if (process != null) {
                    process.destroy();
                }
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
                if (successStream != null) {
                    successStream.close();
                }
            } catch (Exception e) {
            }
        }
        return result;
    }

    public static void startUpApkActivity(Context context, String fileName){
        Uri uri = Uri.fromFile(new File(fileName));
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(installIntent);
    }



    public static boolean isRoot() {
        return new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
    }


    static void LogE(String str){
        Log.e("AppUpdateService", str);
    }
}